﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;

namespace KstopaCommon
{
    public class CsvHelper
    {
        Semaphore sem;
        public string[] FileName { get; set; }

        public CsvHelper(int num)
        {
            FileName = new string[num];
            sem = new Semaphore(1, 1);
        }

        public void ExportToCsv(int index, StringBuilder stringbuilder)
        {
            sem.WaitOne();
            //FileInfo info = new FileInfo(FileName[index]);
            //if (info.Exists == false)
            //{
            //    info.Create();
            //}
            //FileStream fs = new FileStream(fileName, System.IO.FileMode.Create, System.IO.FileAccess.Write);
            // 追加数据，如果文件不存在则创建，如果存在则追加
            FileStream fs = new FileStream(FileName[index], System.IO.FileMode.Append, System.IO.FileAccess.Write, FileShare.ReadWrite);
            StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.Default); // 防止中文乱码
            //StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.UTF8);
            sw.Write(stringbuilder.ToString());
            sw.Close();
            fs.Close();
            sem.Release();
        }
    }
}
